<template>
  <div class="login-container">
    <!-- 登录页头部 -->
    <div class="login-header animate__animated animate__fadeInDown">
      <div class="flex-y-center">
        <el-switch
          v-model="isDark"
          inline-prompt
          active-icon="Moon"
          inactive-icon="Sunny"
          @change="toggleTheme"
        />
        <lang-select class="ml-2 cursor-pointer" />
      </div>
    </div>

    <!-- 背景动效 -->
    <div class="area">
      <ul v-if="!isDark" class="circles">
        <li v-for="i in 10" :key="i" />
      </ul>
      <div v-if="isDark" class="radar-container">
        <div class="radar-circle" />
        <div class="radar-sweep" />
      </div>
    </div>

    <!-- 登录页内容 -->
    <div class="login-content">
      <div class="login-banner animate__animated animate__fadeInLeft">
        <div class="tech-lines" />
        <img
          src="@/assets/images/air-combat-game.svg"
          alt="空中博弈系统插图"
          class="login-illustration"
        />
        <div class="banner-content">
          <h1 class="welcome-text">欢迎使用</h1>
          <div class="type-container">
            <p class="system-intro">自适应式游戏用户系统</p>
            <span class="typing-cursor">|</span>
          </div>
          <p class="system-desc">专业、高效、智能的自适应式游戏用户系统</p>
        </div>
      </div>

      <div class="login-form-container animate__animated animate__fadeInRight">
        <div class="flying-elements">
          <div v-for="i in 5" :key="i" class="flying-element" />
        </div>

        <el-form ref="loginFormRef" :model="loginFormData" :rules="loginRules" class="login-form">
          <div class="form-title">
            <h2>自适应式游戏用户系统</h2>
            <div class="form-subtitle">安全高效的游戏平台</div>
            <el-dropdown style="position: absolute; right: 0">
              <div class="cursor-pointer hover-scale">
                <el-icon>
                  <arrow-down />
                </el-icon>
              </div>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item>
                    <el-tag>{{ defaultSettings.version }}</el-tag>
                  </el-dropdown-item>
                  <el-dropdown-item @click="setLoginCredentials('root', '123456')">
                    超级管理员：root/123456
                  </el-dropdown-item>
                  <el-dropdown-item @click="setLoginCredentials('admin', '123456')">
                    系统管理员：admin/123456
                  </el-dropdown-item>
                  <el-dropdown-item @click="setLoginCredentials('test', '123456')">
                    测试小游客：test/123456
                  </el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </div>

          <!-- 用户名 -->
          <el-form-item prop="username">
            <div class="input-wrapper" :class="{ focused: usernameFocused }">
              <el-icon class="mx-2 input-icon">
                <User />
              </el-icon>
              <el-input
                ref="username"
                v-model="loginFormData.username"
                :placeholder="$t('login.username')"
                name="username"
                size="large"
                class="h-[48px]"
                @focus="usernameFocused = true"
                @blur="usernameFocused = false"
              />
            </div>
          </el-form-item>

          <!-- 密码 -->
          <el-tooltip :visible="isCapslock" :content="$t('login.capsLock')" placement="right">
            <el-form-item prop="password">
              <div class="input-wrapper" :class="{ focused: passwordFocused }">
                <el-icon class="mx-2 input-icon">
                  <Lock />
                </el-icon>
                <el-input
                  v-model="loginFormData.password"
                  :placeholder="$t('login.password')"
                  type="password"
                  name="password"
                  size="large"
                  class="h-[48px] pr-2"
                  show-password
                  @focus="passwordFocused = true"
                  @blur="passwordFocused = false"
                  @keyup="checkCapslock"
                  @keyup.enter="handleLoginSubmit"
                />
              </div>
            </el-form-item>
          </el-tooltip>

          <!-- 验证码 -->
          <el-form-item prop="captchaCode">
            <div class="input-wrapper" :class="{ focused: captchaFocused }">
              <div class="i-svg:captcha mx-2 input-icon" />
              <el-input
                v-model="loginFormData.captchaCode"
                auto-complete="off"
                size="large"
                class="flex-1"
                :placeholder="$t('login.captchaCode')"
                @focus="captchaFocused = true"
                @blur="captchaFocused = false"
                @keyup.enter="handleLoginSubmit"
              />

              <el-image :src="captchaBase64" class="captcha-img" @click="getCaptcha" />
            </div>
          </el-form-item>

          <div class="flex-x-between w-full py-1">
            <el-checkbox>
              <span class="remember-text">{{ $t("login.rememberMe") }}</span>
            </el-checkbox>

            <el-link type="primary" href="/forget-password" class="forget-link">
              {{ $t("login.forgetPassword") }}
            </el-link>
          </div>

          <!-- 登录按钮 -->
          <el-button
            :loading="loading"
            type="primary"
            size="large"
            class="login-button w-full"
            @click.prevent="handleLoginSubmit"
          >
            <span v-if="!loading">{{ $t("login.login") }}</span>
            <span v-else>登录中...</span>
          </el-button>

          <!-- 第三方登录 -->
          <!-- <el-divider>
            <el-text size="small">{{ $t("login.otherLoginMethods") }}</el-text>
          </el-divider>
          <div class="third-party-login">
            <div class="i-svg:wechat" />
            <div class="i-svg:qq" />
            <div class="i-svg:github" />
            <div class="i-svg:gitee" />
          </div> -->
        </el-form>
      </div>
    </div>

    <!-- 登录页底部 -->
    <div class="login-footer animate__animated animate__fadeInUp">
      <el-text size="small">
        Copyright © 2021 - 2024 youlai.tech All Rights Reserved.
        <el-link :underline="false" href="http://beian.miit.gov.cn/" target="_blank">
          皖ICP备20006496号-2
        </el-link>
      </el-text>
    </div>
  </div>
</template>

<script setup lang="ts">
import { LocationQuery, useRoute } from "vue-router";
import { useI18n } from "vue-i18n";

import AuthAPI, { type LoginFormData } from "@/api/auth";
import router from "@/router";

import type { FormInstance } from "element-plus";

import defaultSettings from "@/settings";
import { ThemeEnum } from "@/enums/ThemeEnum";

import { useSettingsStore, useUserStore, useDictStore } from "@/store";
import "animate.css";

const userStore = useUserStore();
const settingsStore = useSettingsStore();
const dictStore = useDictStore();

const route = useRoute();
const { t } = useI18n();
const loginFormRef = ref<FormInstance>();

const isDark = ref(settingsStore.theme === ThemeEnum.DARK); // 是否暗黑模式
const loading = ref(false); // 按钮 loading 状态
const isCapslock = ref(false); // 是否大写锁定
const captchaBase64 = ref(); // 验证码图片Base64字符串

// 输入框焦点状态
const usernameFocused = ref(false);
const passwordFocused = ref(false);
const captchaFocused = ref(false);

const loginFormData = ref<LoginFormData>({
  username: "admin",
  password: "123456",
  captchaKey: "",
  captchaCode: "",
});

const loginRules = computed(() => {
  return {
    username: [
      {
        required: true,
        trigger: "blur",
        message: t("login.message.username.required"),
      },
    ],
    password: [
      {
        required: true,
        trigger: "blur",
        message: t("login.message.password.required"),
      },
      {
        min: 6,
        message: t("login.message.password.min"),
        trigger: "blur",
      },
    ],
    captchaCode: [
      {
        required: true,
        trigger: "blur",
        message: t("login.message.captchaCode.required"),
      },
    ],
  };
});

// 获取验证码
function getCaptcha() {
  AuthAPI.getCaptcha().then((data) => {
    loginFormData.value.captchaKey = data.captchaKey;
    captchaBase64.value = data.captchaBase64;
  });
}

// 登录
async function handleLoginSubmit() {
  loginFormRef.value?.validate((valid: boolean) => {
    if (valid) {
      loading.value = true;
      userStore
        .login(loginFormData.value)
        .then(async () => {
          await userStore.getUserInfo();
          // 需要在路由跳转前加载字典数据，否则会出现字典数据未加载完成导致页面渲染异常
          await dictStore.loadDictionaries();
          // 跳转到登录前的页面
          const { path, queryParams } = parseRedirect();
          router.push({ path: path, query: queryParams });
        })
        .catch(() => {
          getCaptcha();
        })
        .finally(() => {
          loading.value = false;
        });
    }
  });
}

/**
 * 解析 redirect 字符串 为 path 和  queryParams
 *
 * @returns { path: string, queryParams: Record<string, string> } 解析后的 path 和 queryParams
 */
function parseRedirect(): {
  path: string;
  queryParams: Record<string, string>;
} {
  const query: LocationQuery = route.query;
  const redirect = (query.redirect as string) ?? "/";

  const url = new URL(redirect, window.location.origin);
  const path = url.pathname;
  const queryParams: Record<string, string> = {};

  url.searchParams.forEach((value, key) => {
    queryParams[key] = value;
  });

  return { path, queryParams };
}

// 主题切换
const toggleTheme = () => {
  const newTheme = settingsStore.theme === ThemeEnum.DARK ? ThemeEnum.LIGHT : ThemeEnum.DARK;
  settingsStore.changeTheme(newTheme);
};

// 检查输入大小写
function checkCapslock(event: KeyboardEvent) {
  // 防止浏览器密码自动填充时报错
  if (event instanceof KeyboardEvent) {
    isCapslock.value = event.getModifierState("CapsLock");
  }
}

// 设置登录凭证
const setLoginCredentials = (username: string, password: string) => {
  loginFormData.value.username = username;
  loginFormData.value.password = password;
};

onMounted(() => {
  getCaptcha();
});
</script>

<style lang="scss" scoped>
.login-container {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 100%;
  height: 100vh;
  overflow: hidden;
  position: relative;
  background: var(--el-bg-color);
}

.login-header {
  position: absolute;
  top: 0;
  display: flex;
  justify-content: right;
  width: 100%;
  padding: 15px;
  z-index: 10;
}

.login-content {
  display: flex;
  width: 80%;
  max-width: 1200px;
  height: 600px;
  border-radius: 20px;
  overflow: hidden;
  box-shadow: 0 15px 50px rgba(0, 0, 0, 0.1);
  background-color: var(--el-bg-color-overlay);
  backdrop-filter: blur(15px);
  animation: floatEffect 6s ease-in-out infinite;
  position: relative;
  z-index: 2;

  @media (width <= 992px) {
    flex-direction: column;
    width: 90%;
    height: auto;
    animation: none;
  }
}

.login-banner {
  flex: 1;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  padding: 40px;
  background: linear-gradient(135deg, #3b82f6 0%, #1d4ed8 100%);
  color: #fff;
  position: relative;
  overflow: hidden;

  @media (width <= 992px) {
    display: none;
  }

  .tech-lines {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background:
      linear-gradient(90deg, rgba(255, 255, 255, 0.1) 1px, transparent 1px),
      linear-gradient(0deg, rgba(255, 255, 255, 0.1) 1px, transparent 1px);
    background-size: 30px 30px;
    transform: perspective(500px) rotateX(30deg);
    transform-origin: center center;
    animation: gridMove 20s linear infinite;
  }

  .login-illustration {
    width: 90%;
    max-width: 320px;
    filter: drop-shadow(0 10px 15px rgba(0, 0, 0, 0.3));
    animation: floatLogo 5s ease-in-out infinite;
    transform-origin: center center;
    margin-bottom: 20px;
  }

  .banner-content {
    text-align: center;
    z-index: 1;
  }

  .welcome-text {
    font-size: 2.8rem;
    font-weight: 700;
    margin-bottom: 10px;
    background: linear-gradient(45deg, #ffffff, #e0f2fe);
    -webkit-background-clip: text;
    -webkit-text-fill-color: transparent;
    text-shadow: 0 5px 10px rgba(0, 0, 0, 0.2);
  }

  .type-container {
    display: flex;
    align-items: center;
    justify-content: center;
    position: relative;
    margin-bottom: 15px;

    .system-intro {
      font-size: 1.3rem;
      font-weight: 500;
      letter-spacing: 1px;
    }

    .typing-cursor {
      font-size: 1.3rem;
      animation: blink 1s step-end infinite;
      margin-left: 2px;
    }
  }

  .system-desc {
    font-size: 0.95rem;
    opacity: 0.9;
    max-width: 300px;
    text-align: center;
    line-height: 1.5;
    letter-spacing: 0.5px;
  }
}

.login-form-container {
  flex: 1;
  display: flex;
  justify-content: center;
  padding: 40px;
  position: relative;
  overflow: hidden;

  @media (width <= 992px) {
    padding: 30px 20px;
  }

  .flying-elements {
    position: absolute;
    width: 100%;
    height: 100%;
    top: 0;
    left: 0;
    pointer-events: none;
  }

  .flying-element {
    position: absolute;
    width: 20px;
    height: 20px;
    border-radius: 50%;
    background: linear-gradient(135deg, rgba(59, 130, 246, 0.2), rgba(37, 99, 235, 0.1));
    animation: flyAround 15s linear infinite;

    &:nth-child(1) {
      top: 20%;
      left: 10%;
      width: 15px;
      height: 15px;
      animation-duration: 17s;
      animation-delay: 0s;
    }

    &:nth-child(2) {
      top: 60%;
      left: 80%;
      width: 12px;
      height: 12px;
      animation-duration: 22s;
      animation-delay: 1s;
    }

    &:nth-child(3) {
      top: 30%;
      left: 60%;
      width: 18px;
      height: 18px;
      animation-duration: 19s;
      animation-delay: 2s;
    }

    &:nth-child(4) {
      top: 70%;
      left: 20%;
      width: 10px;
      height: 10px;
      animation-duration: 24s;
      animation-delay: 3s;
    }

    &:nth-child(5) {
      top: 15%;
      left: 70%;
      width: 16px;
      height: 16px;
      animation-duration: 21s;
      animation-delay: 4s;
    }
  }
}

.login-form {
  width: 100%;
  max-width: 400px;
  position: relative;
  z-index: 1;
}

.form-title {
  position: relative;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 0 0 30px;
  text-align: center;

  h2 {
    font-size: 1.8rem;
    font-weight: 600;
    margin-bottom: 8px;
    background: linear-gradient(45deg, #3b82f6, #1d4ed8);
    -webkit-background-clip: text;
    -webkit-text-fill-color: transparent;
  }

  .form-subtitle {
    font-size: 0.9rem;
    color: var(--el-text-color-secondary);
    letter-spacing: 1px;
  }
}

.input-wrapper {
  display: flex;
  align-items: center;
  width: 100%;
  border-radius: 12px;
  transition: all 0.3s;

  .input-icon {
    color: var(--el-text-color-secondary);
    transition: all 0.3s;
  }

  &.focused {
    .input-icon {
      color: #3b82f6;
    }
  }
}

:deep(.el-form-item) {
  background: var(--el-input-bg-color);
  border: 1px solid var(--el-border-color);
  border-radius: 12px;
  transition: all 0.3s;
  margin-bottom: 18px;

  &:hover {
    box-shadow: 0 0 0 2px rgba(59, 130, 246, 0.1);
  }
}

:deep(.el-input) {
  .el-input__wrapper {
    padding: 0;
    background-color: transparent;
    box-shadow: none;

    &.is-focus,
    &:hover {
      box-shadow: none !important;
    }

    input:-webkit-autofill {
      transition: background-color 1000s ease-in-out 0s;
    }
  }
}

.captcha-img {
  height: 48px;
  cursor: pointer;
  border-top-right-radius: 12px;
  border-bottom-right-radius: 12px;
  transition: all 0.3s;

  &:hover {
    opacity: 0.9;
    transform: scale(1.05);
  }
}

.login-button {
  height: 50px;
  font-weight: 600;
  font-size: 1.05rem;
  background: linear-gradient(45deg, #3b82f6, #1d4ed8);
  border: none;
  border-radius: 12px;
  margin-top: 15px;
  transition: all 0.3s;
  position: relative;
  overflow: hidden;
  letter-spacing: 1px;

  &:hover {
    transform: translateY(-3px);
    box-shadow: 0 7px 15px rgba(59, 130, 246, 0.3);
  }

  &:active {
    transform: translateY(-1px);
  }

  &::before {
    content: "";
    position: absolute;
    top: 0;
    left: -100%;
    width: 100%;
    height: 100%;
    background: linear-gradient(90deg, transparent, rgba(255, 255, 255, 0.2), transparent);
    transition: all 0.6s;
  }

  &:hover::before {
    left: 100%;
  }
}

.hover-scale {
  transition: transform 0.3s;
  &:hover {
    transform: scale(1.2);
  }
}

.remember-text,
.forget-link {
  opacity: 0.85;
  transition: all 0.3s;

  &:hover {
    opacity: 1;
  }
}

.login-footer {
  position: absolute;
  bottom: 0;
  width: 100%;
  padding: 15px;
  text-align: center;
  z-index: 1;
}

// 背景动画
.area {
  position: absolute;
  width: 100%;
  height: 100vh;
  z-index: 0;
}

.circles {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  overflow: hidden;
  margin: 0;
  padding: 0;
}

.circles li {
  position: absolute;
  display: block;
  list-style: none;
  width: 20px;
  height: 20px;
  background: rgba(59, 130, 246, 0.2);
  animation: animate 25s linear infinite;
  bottom: -150px;
  border-radius: 50%;
  box-shadow: 0 0 15px rgba(59, 130, 246, 0.1);
}

.circles li:nth-child(1) {
  left: 25%;
  width: 80px;
  height: 80px;
  animation-delay: 0s;
}

.circles li:nth-child(2) {
  left: 10%;
  width: 20px;
  height: 20px;
  animation-delay: 2s;
  animation-duration: 12s;
}

.circles li:nth-child(3) {
  left: 70%;
  width: 20px;
  height: 20px;
  animation-delay: 4s;
}

.circles li:nth-child(4) {
  left: 40%;
  width: 60px;
  height: 60px;
  animation-delay: 0s;
  animation-duration: 18s;
}

.circles li:nth-child(5) {
  left: 65%;
  width: 20px;
  height: 20px;
  animation-delay: 0s;
}

.circles li:nth-child(6) {
  left: 75%;
  width: 110px;
  height: 110px;
  animation-delay: 3s;
}

.circles li:nth-child(7) {
  left: 35%;
  width: 150px;
  height: 150px;
  animation-delay: 7s;
}

.circles li:nth-child(8) {
  left: 50%;
  width: 25px;
  height: 25px;
  animation-delay: 15s;
  animation-duration: 45s;
}

.circles li:nth-child(9) {
  left: 20%;
  width: 15px;
  height: 15px;
  animation-delay: 2s;
  animation-duration: 35s;
}

.circles li:nth-child(10) {
  left: 85%;
  width: 150px;
  height: 150px;
  animation-delay: 0s;
  animation-duration: 11s;
}

// 雷达动画 (暗黑模式)
.radar-container {
  position: absolute;
  width: 800px;
  height: 800px;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  opacity: 0.3;
}

.radar-circle {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  border: 1px solid rgba(99, 102, 241, 0.3);
  border-radius: 50%;

  &:after {
    content: "";
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    width: 70%;
    height: 70%;
    border: 1px solid rgba(99, 102, 241, 0.3);
    border-radius: 50%;
  }

  &:before {
    content: "";
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    width: 40%;
    height: 40%;
    border: 1px solid rgba(99, 102, 241, 0.3);
    border-radius: 50%;
  }
}

.radar-sweep {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;

  &:after {
    content: "";
    position: absolute;
    top: 0;
    left: 50%;
    width: 50%;
    height: 100%;
    background: linear-gradient(90deg, transparent, rgba(99, 102, 241, 0.3));
    transform-origin: left center;
    animation: radarSweep 5s linear infinite;
  }
}

@keyframes animate {
  0% {
    transform: translateY(0) rotate(0deg);
    opacity: 1;
    border-radius: 0;
  }
  100% {
    transform: translateY(-1000px) rotate(720deg);
    opacity: 0;
    border-radius: 50%;
  }
}

@keyframes flyAround {
  0% {
    transform: translate(0, 0);
  }
  25% {
    transform: translate(100px, 50px);
  }
  50% {
    transform: translate(50px, 100px);
  }
  75% {
    transform: translate(-50px, 50px);
  }
  100% {
    transform: translate(0, 0);
  }
}

@keyframes floatEffect {
  0%,
  100% {
    transform: translateY(0px);
  }
  50% {
    transform: translateY(-15px);
  }
}

@keyframes floatLogo {
  0%,
  100% {
    transform: translateY(0) rotate(0deg);
  }
  50% {
    transform: translateY(-10px) rotate(2deg);
  }
}

@keyframes gridMove {
  0% {
    background-position: 0 0;
  }
  100% {
    background-position: 30px 30px;
  }
}

@keyframes blink {
  0%,
  100% {
    opacity: 1;
  }
  50% {
    opacity: 0;
  }
}

@keyframes radarSweep {
  0% {
    transform: rotate(0deg);
  }
  100% {
    transform: rotate(360deg);
  }
}

// 暗黑模式
html.dark {
  .login-banner {
    background: linear-gradient(135deg, #334155 0%, #1e293b 100%);
  }

  .form-title h2 {
    background: linear-gradient(45deg, #6366f1, #4f46e5);
    -webkit-background-clip: text;
  }

  .login-button {
    background: linear-gradient(45deg, #6366f1, #4f46e5);
  }

  .circles li {
    background: rgba(99, 102, 241, 0.2);
  }

  .flying-element {
    background: linear-gradient(135deg, rgba(99, 102, 241, 0.2), rgba(79, 70, 229, 0.1));
  }

  .input-wrapper.focused .input-icon {
    color: #6366f1;
  }

  :deep(.el-form-item:hover) {
    box-shadow: 0 0 0 2px rgba(99, 102, 241, 0.1);
  }

  .login-button:hover {
    box-shadow: 0 7px 15px rgba(99, 102, 241, 0.3);
  }
}
</style>
